package org.example;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class MyClassPathXmlApplicationContext {
    private String xmlPath;
    public MyClassPathXmlApplicationContext(String xmlPath) {
        this.xmlPath=xmlPath;
    }
    public Class<?> getBean(String beanId) throws Exception{
        if(beanId.equals("")||StringUtils.isEmpty(beanId)){
            throw new Exception("beanId不能为空!");
        }
        List<Element> readXML=readXML();
        if(readXML==null||readXML.isEmpty()){
            throw new Exception("xml中未配置bean!");
        }
        String className=findByElementClass(readXML,beanId);
        if(StringUtils.isEmpty(className)){
            throw new Exception("该bean对象没有配置class");
        }
        return newInstance(className);
    }
    public String findByElementClass(List<Element> readXML,String beanId) throws Exception{
        for(Element element:readXML){
            String xmlBeanId=element.attributeValue("id");
            if(StringUtils.isEmpty(xmlBeanId)){
                throw new Exception("未获取到bean节点信息");
            }
            if(xmlBeanId.equals(beanId)){
                String xmlClass=element.attributeValue("class");
                return xmlClass;
            }
        }
        return null;
    }
    public Class<?> newInstance(String className) throws ClassNotFoundException{
        Class<?> classInfo=Class.forName(className);
        return classInfo;
    }
    public List<Element> readXML() throws DocumentException{
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(getResourceAsStream(xmlPath));
        Element rootElement = document.getRootElement();
        List<Element> elements=rootElement.elements();
        return elements;
    }
    public InputStream getResourceAsStream(String xmlPath) {
        return this.getClass().getClassLoader().getResourceAsStream(xmlPath);
    }
}
